﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Marmat.Forms.Skin
{
    public partial class Switch : Control, ISkinControl
    {
        public Switch()
        {
            InitializeComponent();
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            base.BackColor = Color.Transparent;
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();
            // 
            // Switch
            // 
            this.Name = "Switch";
            this.Size = new System.Drawing.Size(48, 23);
            this.ResumeLayout(false);

        }

        protected override void OnSizeChanged(EventArgs e)
        {
            this.Refresh();
            base.OnSizeChanged(e);
        }

        private void Refresh()
        {
            this._circle = Math.Min(Math.Min(this.Height, this.Width) / 2, this._circle);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (this.Height <= 0 || this.Width <= 0)
                return;
            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            var rec = new Rectangle(0, 0, this.Width - 1, this.Height - 1);
            Color color = this.Checked ? this.SelectedColor : this.UnselectedColor;
            if (!this.Enabled)
            {
                color = color.Blend(Color.FromArgb(Convert.ToInt32(256 * 0.5), Color.White));
            }
            using (var bush = new SolidBrush(color))
            {
                GraphicsPath path = rec.GetRoundPath(this._circle);
                e.Graphics.FillPath(bush, path);
            }
            //绘制圆
            int yun_size = this.Height - Interval * 2;
            if (yun_size <= 1) return;
            Rectangle yun_rec = default;
            using (var bush = new SolidBrush(Color.White))
            {
                if (Checked)
                    yun_rec = new Rectangle(this.Width - Interval - yun_size - 1, this.Height - yun_size - Interval, yun_size - 1, yun_size - 1);
                else
                    yun_rec = new Rectangle(Interval, Interval, yun_size - 1, yun_size - 1);
                var inside_circle = Math.Min(yun_rec.Width / 2, this._circle);
                GraphicsPath path = yun_rec.GetRoundPath(inside_circle);
                e.Graphics.FillPath(bush, path);
            }
        }

        protected override void OnClick(EventArgs e)
        {
            this.Checked = !this.Checked;
            this.Invalidate();
            base.OnClick(e);
        }
    }
}
